home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!netnews
- From: miker3@ix.netcom.com (Mike Rubenstein)
- Newsgroups: comp.lang.c
- Subject: Re: returning a string from a function
- Date: Fri, 12 Jan 1996 12:13:53 GMT
- Organization: Netcom
- Message-ID: <30f64e6a.41247232@nntp.ix.netcom.com>
- References: <4d4uh8$q46@mailhost.mwmicro.com>
- NNTP-Posting-Host: ix-dc11-03.ix.netcom.com
- X-NETCOM-Date: Fri Jan 12 4:13:44 AM PST 1996
- X-Newsreader: Forte Agent .99c/16.141
-
- aschlies@citynet.net (Tony Schliesser) wrote:
-
- |>I am learning C with the aid of only a book. I am at an inpass in
- |>this process. I have a small function that needs to return a string
- |>back to the main routine. I have the following prototype:
- |>
- |>char function_name(char in_string[80])
- |>
- |>{
- |> char value[80];
- |>
- |> ...value takes on part of the value of the last 10 characters
- |> of in_string.
- |>
- |> return(value);
- |>}
- |>
- |>
- |>jWhen this function is done, it only returns the first character. I
- |>"watched" the program execution and it shows that value indeed has
- the
- |>last 10 characters. Any clues as to why the calling routine only
- gets
- |>the one character??
- |>
- |>Also, I wrote the routine that copies the last 10 characters. Is
- there
- |>a lib. function that does that for me?? Did I reinvent the wheel?
-
- A few problems.
-
- First, you've defined the function as returning a single char. If you
- want to return a string, you must define it as returning a pointer to
- char.
-
- Since you must return a pointer, the thing it points to must live
- after the function exits. An auto variable like value in you function
- is deallocated when it exits.
-
- Either
-
- 1. Make value static (in which case users of the function must
-
- realize that the returned value becomes invalid the next
- time the function is called).
-
- 2. allocate it with malloc() (or such) (in which case the
- caller must realize that it must be freed).
-
- 3. return a pointer into the argument (in which case the
- caller must realize that the return is valid only as long
- as the argument string is unchanged.
-
- Something like
-
- char* function_name(char in_string[80])
- {
- static char value[80];
-
- /* do your thing */
-
- return(value);
- }
-
- You don't show code for your copy, but it sounds like you could use
- strcpy() or strncpy().
-
- You should be aware that in_string is really a pointer to char.
- Nothing in the language constrains it to being only 80 characters
- long, so make sure your function doesn't mess up with longer strings.
-
-
- Michael M Rubenstein
-